package com.tobie.schedule.task;

import com.tobie.schedule.controller.ScheduleController;
import com.tobie.schedule.pojo.entity.ScheduleEntity;
import com.tobie.schedule.service.IScheduleService;
import lombok.val;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Tobieance
 * @description
 * @date 2023-11-16 09:14
 */
@Component
@EnableScheduling
public class ScheduleAlertTask {
    @Resource
    private ScheduleController scheduleController;
    @Resource
    private IScheduleService scheduleService;

    //3.添加定时任务
    @Scheduled(cron = "0/5 * * * * ?")
    //直接指定时间间隔，5秒执行一次
    private void configureTasks() throws ParseException {
        //获取userId，并取得所有还未到期的日程
        List<ScheduleEntity> schedules = scheduleService.selectAlertSchedule(scheduleController.getAlertUserId());
        List<ScheduleEntity> alertSchedules=new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date currentDate=new Date();
        for (val schedule:schedules) {
            //解析日期字符串
            Date targetDate = format.parse(schedule.getScheduleDate());
            //判断日期是否已经超过当前时间
            if (currentDate.compareTo(targetDate) >= 0) {
                //设置状态为已提醒
                schedule.setScheduleStatus(1);
                alertSchedules.add(schedule);
                //设置提醒状态为1
                scheduleService.setAlert(schedule);
            }
        }
        //发送要提醒的数据
        scheduleController.sendScheduleEntity(alertSchedules);
    }
}
